package cn.lutu.domain.service.impl;

import cn.lutu.cache.InvoiceCacheRepository;
import cn.lutu.domain.repository.InvoiceRepository;
import cn.lutu.domain.repository.OrderRepository;
import cn.lutu.domain.service.InvoiceService;

import cn.lutu.protocol.dto.InvoiceAddDTO;
import cn.lutu.protocol.entity.Invoice;
import cn.lutu.protocol.entity.Order;
import cn.lutu.protocol.vo.InvoiceVO;
import cn.lutu.protocol.vo.OrderListVO;
import cn.lutu.protocol.vo.adminVO.AdminInvoiceVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @date 2023-06-03
 * @author luoyinhan
 * */
@Service
@Slf4j
public class InvoiceServiceImpl implements InvoiceService {
    @Autowired
    InvoiceRepository invoiceRepository;

    @Autowired
    OrderRepository orderRepository;

    @Autowired
    InvoiceCacheRepository invoiceCacheRepository;

    @Override
    public void addInvoice(InvoiceAddDTO invoiceAddDTO, Long id) {
        log.debug("开始处理添加发票的业务，参数：{}", invoiceAddDTO);
        Invoice invoice=new Invoice();
        BeanUtils.copyProperties(invoiceAddDTO,invoice);
        invoice.setUserId(id);
        invoice.setSubject(invoiceAddDTO.getSubject());
        invoice.setStatus("APPLYING");
        System.out.println(invoice);
        invoiceRepository.insert(invoice);

        Order order=new Order();
        order.setId(invoiceAddDTO.getOrderId());
        order.setStatus("APPLYING");
        orderRepository.updateById(order);
    }

    @Override
    public void updateInvoice(Long id, String status) {
        log.debug("开始处理更新发票的业务，参数：{},{}", id,status);
        Invoice invoice=new Invoice();
        invoice.setId(id);
        invoice.setStatus(status);
        invoiceRepository.updateById(invoice);
    }

    @Override
    public InvoiceVO selectByOrderId(Long orderId) {
        log.debug("开始处理查看发票的业务，参数：{}", orderId);
        return invoiceRepository.selectByOrderId(orderId);
    }

    @Override
    public List<InvoiceVO> selectByUserId(Long userId) {
        log.debug("开始处理查看用户所有发票的业务，参数：{}", userId);
        return invoiceRepository.selectByUserId(userId);
    }

    @Override
    public List<InvoiceVO> selectByKeyword(String keyword,Long userId) {
        log.debug("开始处理搜索发票的业务，参数：{}", keyword);
        return invoiceRepository.selectByKeyword(keyword,userId);
    }

    @Override
    public List<AdminInvoiceVO> selectAllInvoices() {
        log.debug("开始处理搜索所有发票的业务");
        return invoiceCacheRepository.readInvoice();
    }

    @Override
    public void rebuildListCache() {
        log.debug("开始处理重建缓存中的发票列表的业务");
        invoiceCacheRepository.delete();
        List<AdminInvoiceVO> list = invoiceRepository.selectAll();
        invoiceCacheRepository.insertRedis(list);
    }
}
